package com.serkol.ams.service.impl;


import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.CharUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serkol.ams.bean.MyPage;
import com.serkol.ams.entity.Famous;
import com.serkol.ams.service.FamousService;
import com.serkol.ams.mapper.FamousMapper;
import com.serkol.config.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.CharsetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpHeaders;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author Administrator
 * @description 针对表【famous】的数据库操作Service实现
 * @createDate 2025-01-16 13:28:40
 */
@Service
public class FamousServiceImpl extends ServiceImpl<FamousMapper, Famous>
        implements FamousService {
    @Autowired
    private RedisUtil redisUtil;

   // @Cacheable(unless="#result == null",cacheNames = "famous", key = "'findByName::'+#name")
    @Override
    public Famous findByName(String name) {
        System.out.println("findByName::" + name);
        boolean isChinese = containsChinese(name);
        System.out.println("isChinese:" + isChinese);
        if (isChinese) {
            Famous famous2 = new Famous();
            famous2.setName(name);
            System.out.println(famous2);
            /**/
            String[] strings = splitName(name);
            StringBuilder builder = new StringBuilder();
            if (strings.length > 0) {
                Famous famous = new Famous();
                String string = strings[0].trim();
                famous.setName(string);
                System.out.println("FFFFF:"+famous);
                String nameUg = findByMyName(string);
                if (nameUg == null) {
                    nameUg = translate(strings[0]);
                    if (nameUg != null) {
                        famous.setNameUg(nameUg);
                        this.save(famous);
                    }
                }

                builder.append(nameUg);
                System.out.println("nameUg:"+nameUg);
                if (strings.length > 1) {

                    Famous famous1 = new Famous();
                    String string1 = strings[1].trim();
                    famous1.setName(string1);
                    nameUg = findByMyName(string1);
                    if (nameUg == null) {
                        nameUg = translate(strings[1]);
                        if (nameUg != null) {
                            famous1.setNameUg(nameUg.trim());
                            this.save(famous1);
                        }
                    }
                    if (nameUg != null) {
                        builder.append(".".trim());
                        builder.append(nameUg.trim());
                    }
                }
                System.out.println("nameUg:"+nameUg);

                famous2.setNameUg(builder.toString().trim());
                System.out.println(famous2);
                return famous2;
            } else {
                return null;
            }
        }else {
            return null;
        }

    }

    @Override
    public MyPage<Famous> findByPage(int pageSize, int current, int state) {
        LambdaQueryWrapper<Famous> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(Famous::getState, state).orderByAsc(Famous::getName);

      Page<Famous> page = new Page<>(current, pageSize);
      IPage<Famous> data = this.baseMapper.selectPage(page, queryWrapper);
        return MyPage.parsePage(data);
    }

    private String findByMyName(String string) {
        String key = "famous::db:" + string.trim();
        if (redisUtil.hasKey(key)) {
            return redisUtil.get(key).toString();
        } else {
            LambdaQueryWrapper<Famous> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Famous::getName, string.trim());
            queryWrapper.last("limit 1");
            Famous one = this.getOne(queryWrapper);
            if (one != null) {
                redisUtil.set(key, one.getNameUg());
                return one.getNameUg();
            } else {
                return null;
            }
        }
    }

    private String[] splitName(String name) {
        // 使用正则表达式分割名字
        return name.split("[·.，,。 \t\r\n]");
    }

    private String translate(String text) {
        try {
            HttpClient client = HttpClient.newHttpClient();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("text", text);
            jsonObject.put("source_lang", "zh");
            jsonObject.put("target_lang", "ug");
            jsonObject.put("trans_type", "m");
            String requestBody = jsonObject.toJSONString();
            String authKey = "r/SW9xGsTZYPzG2Xr0FFlaEhByShKp3QKv/oT75XY8/5Of5sZq+ldVwtK3lcXDA2"; // 替换为实际的授权密钥
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(new URI("https://translate.wuyoufanyi.com/api/Translate"))
                    .header("Authorization", "Bearer " + authKey)
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) { // 成功
                JSONObject myResponse = JSONObject.parseObject(response.body());
                String data = myResponse.getString("data");
                System.out.println("Translation: " + data);
                return data;
            } else {
                System.out.println("POST请求失败，响应码：" + response.statusCode());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean containsChinese(String str) {
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        System.out.println(str);
        String regex = ".*[\u4e00-\u9fa5]+.*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }
}




